package com.pxxy.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.pxxy.mall.product.dao.CategoryBrandRelationDao;
import com.pxxy.mall.product.entity.CategoryBrandRelationEntity;
import com.pxxy.mall.product.vo.Catalog2Vo;
import com.pxxy.mall.product.vo.Catalog3Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxxy.common.utils.PageUtils;
import com.pxxy.common.utils.Query;

import com.pxxy.mall.product.dao.CategoryDao;
import com.pxxy.mall.product.entity.CategoryEntity;
import com.pxxy.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private RedissonClient redisson;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = this.baseMapper.selectList(null);
        //一级分类
        List<CategoryEntity> collectOne = entities.stream().filter(t -> t.getParentCid() == 0)
                .map(t -> {
                    t.setChildren(getChildrens(t, entities));
                    return t;
                }).sorted((t1, t2) -> {
                    return (t1.getSort() == null ? 0 : t1.getSort()) - (t2.getSort() == null ? 0 : t2.getSort());
                }).collect(Collectors.toList());


        return collectOne;

    }


    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(t -> t.getParentCid() == root.getCatId())
                .map(t -> {
                    t.setChildren(getChildrens(t, all));
                    return t;
                }).sorted((t1, t2) -> {
                    return (t1.getSort() == null ? 0 : t1.getSort()) - (t2.getSort() == null ? 0 : t2.getSort());
                }).collect(Collectors.toList());
        return children;
    }

    /**
     * 修改类名的同时品牌分类关系表中的名字也要修改
     *
     * @param category
     * @return
     */

    @Caching(evict = {
            @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category", key = "'getCatelogJson'")
    }
    )

    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        if (!StringUtils.isEmpty(category.getName())) {
            CategoryEntity one = this.lambdaQuery().eq(CategoryEntity::getCatId, category.getCatId()).one();
            categoryBrandRelationDao.update(getCategoryBrandRelation(category),
                    new UpdateWrapper<CategoryBrandRelationEntity>()
                            .lambda()
                            .eq(CategoryBrandRelationEntity::getCatelogId, category.getCatId()));
        }
        this.updateById(category);
    }


    /**
     * 找到父节点
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> list = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, list);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().lambda().eq(CategoryEntity::getParentCid, 0));
    }


    private CategoryBrandRelationEntity getCategoryBrandRelation(CategoryEntity entity) {
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setCatelogId(entity.getCatId());
        categoryBrandRelationEntity.setCatelogName(entity.getName());
        return categoryBrandRelationEntity;
    }

    //递归找到父节点
    private List<Long> findParentPath(Long catelogId, List list) {
        list.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0 && byId.getParentCid() != null) {
            this.findParentPath(byId.getParentCid(), list);
        }
        return list;
    }

    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Catalog2Vo>> getCatelogJson() {
        RLock rLock = redisson.getLock("catalogJson_lock");
        rLock.lock();
        //加锁成功
        Map<String, List<Catalog2Vo>> listMap = null;
        try {
            listMap = getStringListMap();
        } finally {
            rLock.unlock();
        }
        return listMap;
    }


    private Map<String, List<Catalog2Vo>> getStringListMap() {
        System.out.println("查询了数据库");
        List<CategoryEntity> level1Categorys = this.getLevel1Categorys();
        Map<String, List<Catalog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查出所有对应一级id的二级分类
            List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().lambda().eq(CategoryEntity::getParentCid, v.getCatId()));
            List<Catalog2Vo> catalog2Vos = entities.stream().map(t -> {
                Catalog2Vo catalog2Vo = new Catalog2Vo();
                catalog2Vo.setCatalog1Id(v.getCatId());
                catalog2Vo.setId(t.getCatId());
                catalog2Vo.setName(t.getName());
                //根据二级分类的id找到相对应的三级分类
                List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().lambda().eq(CategoryEntity::getParentCid, t.getCatId()));
                List<Catalog3Vo> catalog3Vos = categoryEntities.stream().map(item -> {
                    Catalog3Vo catalog3Vo = new Catalog3Vo();
                    catalog3Vo.setCatalog2Id(t.getCatId());
                    catalog3Vo.setId(item.getCatId());
                    catalog3Vo.setName(item.getName());
                    return catalog3Vo;
                }).collect(Collectors.toList());
                //设置二级分类里的三级分类集合
                catalog2Vo.setCatalog3List(catalog3Vos);
                return catalog2Vo;
            }).collect(Collectors.toList());
            return catalog2Vos;
        }));
        return collect;
    }

}